import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { toItemDesc } from '@/utils/itemdesc';
import * as UUID from '@/utils/uuid';
import AccountJS from '@/utils/account';
import { SimplePinYin } from '@/utils/pinyin';

import { Spin, Row, Col, Icon, Form, Button, Avatar, InputNumber, Popconfirm, Modal, Select, Input, Divider } from 'antd';

import styles from './styles.less';

const FormItem = Form.Item;
const { Option } = Select;

const ModelName = "inv";
@connect(({ loading, currency, invItemCategory }) => ({
  loading: loading.models[ModelName],
  iics: invItemCategory.list,
  currencys: currency.list,
}))
@Form.create()
class Comp extends PureComponent {
  state = {
    list: [],

    cUSD: 0,
    cRMB: 0,
  }

  constructor(props) {
    super(props);
    const { getInstance } = props;
    if (typeof getInstance === 'function') {
      getInstance(this);
    }
  }

  componentDidMount() {
    this.setState({
      cUSD: this.props.currencys.filter(r => r.objectName.toUpperCase() === 'USD')[0].id,
      cRMB: this.props.currencys.filter(r => r.objectName.toUpperCase() === 'RMB')[0].id,
    })

    const { inv } = this.props;
    this.setCurrent(inv);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.inv !== this.props.inv) {
      this.setCurrent(nextProps.inv);
    }
  }

  setCurrent(inv) {
    const { dispatch } = this.props;
    this.setState({ list: [] }, () => {
      if (inv && inv.id > 0) {
        dispatch({
          type: `inv/getItemsByInvId`,
          payload: inv.id,
          callback: (resp) => {
            this.setState({ list: resp });
            this.setState({ canEditBox: inv.isLock === 0 });
          }
        })
      }
    });
  }

  remove = (item) => {
    const v2 = this.state.list.filter(r => r.id !== item.id);
    this.setState({ list: v2 });
  }

  addItem = () => {
    const { inv } = this.props;
    // 币种
    let currencyId = 0;
    var preItem = this.state.list[0];  // 先就第一项一个币种.
    if (preItem) {
      currencyId = preItem.currencyId;
    }
    if (currencyId === 0 && inv) { // 如果上一个币种为空，则按下面标准设定币种
      currencyId = inv.invoiceType === 2 ? this.state.cUSD : this.state.cRMB;  //如果是客户帐单，则使用USD，否则使用rmb.
    }

    this.setState({
      list: [
        ...this.state.list,
        {
          id: UUID.uuid2(),
          invItemCategoryId: 0,
          currencyId: currencyId,
          price: 0,
          qty: 1,
        }]
    });
  }

  handleQtyBlur(index) {
    const { form } = this.props;

    var qty = form.getFieldValue(`qty_${index}`);
    var price = form.getFieldValue(`price_${index}`);

    // console.log("NEW QTY", price * qty);
    const amountCell = 'amount_' + index;

    const amountValue = price * qty;

    const avString = AccountJS.format(amountValue);

    console.log("VALUE,STRING", amountValue, avString);

    this.props.form.setFieldsValue({
      [amountCell]: amountValue,
    });

  }

  render() {
    const { loading, form: { getFieldDecorator }, iics, currencys } = this.props;
    const { list, canEditBox } = this.state;

    const formLayout = {
      labelCol: {
        xs: { span: 0 },
        sm: { span: 0 },
        lg: { span: 0 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 },
        lg: { span: 24 },
      },
    };

    return (<div className={styles.container}>
      <Form>
        <Row className={styles.titleRow}>
          <Col span={1} className={styles.leaderCol} style={{ width: '3em' }}>
            <div >
              {/* # */}
              <Icon
                className={styles.dynamic_button}
                style={{ display: canEditBox ? '' : 'none' }}
                type="plus"
                onClick={e => { e.preventDefault(); this.addItem(); }}
              />
            </div>
          </Col>
          <Col span={6} className={styles.labelCol}>费用明细</Col>
          <Col span={4} className={styles.labelCol}>单价</Col>
          <Col span={4} className={styles.labelCol}>数量</Col>
          <Col span={4} className={styles.labelCol}>币种</Col>
          <Col span={4} className={styles.labelCol}>小计</Col>
        </Row>

        <div >
          {
            list.map((item, index) => {
              return <Row className={styles.dataRow} key={item.id}  >
                <Col span={1} className={styles.leaderCol} style={{ width: '3em' }}>
                  <div style={{ display: 'flex', marginTop: '1em', display: canEditBox ? '' : 'none' }}>

                    <Icon
                      className={styles.dynamic_button}
                      // style={{ marginTop: '1em', display: canEditBox ? '' : 'none' }}
                      type="minus"
                      onClick={() => this.remove(item)}
                    />
                  </div>
                </Col>
                <Col span={6} className={styles.labelCol}>
                  <div style={{ display: 'flex' }}>
                    <span style={{ width: '1em', marginTop: '0.6em', marginLeft: '0.5em' }}>{index + 1}、</span>
                    <FormItem {...formLayout} hasFeedback={false} style={{ width: '100%', minWidth: '4em' }}>
                      {getFieldDecorator(`invItemCategoryId_${index}`, {
                        rules: [{ required: true }],
                        initialValue: item ? item.invItemCategoryId : 0,
                      })(
                        <Select

                          allowClear
                          showSearch
                          filterOption={(input, option) => SimplePinYin.selectPinYin(input, option)}
                        >{iics.map(item => <Option key={item.id} value={item.id}>{item.objectName}</Option>)}
                        </Select>
                      )}
                    </FormItem>
                  </div>
                </Col>
                <Col span={4} className={styles.labelCol}>
                  <FormItem {...formLayout} >
                    {getFieldDecorator(`price_${index}`, {
                      rules: [{ required: true, message: '请输入单价' }],
                      initialValue: item.price,
                    })(<InputNumber onBlur={(e) => this.handleQtyBlur(index)} style={{ width: '100%' }} size="small" />)}
                  </FormItem>
                </Col>
                <Col span={4} className={styles.labelCol}>
                  <FormItem {...formLayout}>
                    {getFieldDecorator(`qty_${index}`, {
                      rules: [{ required: true, message: '请输入数量' }],
                      initialValue: item.qty,
                    })(<InputNumber onBlur={(e) => this.handleQtyBlur(index)} style={{ width: '100%' }} size="small" />)}
                  </FormItem>
                </Col>
                <Col span={4} className={styles.labelCol}>
                  <FormItem {...formLayout} hasFeedback={false} >
                    {getFieldDecorator(`currencyId_${index}`, {
                      rules: [{ required: true, message: '请输入币种' }],
                      initialValue: item ? item.currencyId : 0,
                    })(
                      <Select
                        size="small"
                        showSearch
                        optionFilterProp="children"
                        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                      >
                        {currencys.map(item => <Option key={item.id} value={item.id}>{item.objectName}</Option>)}
                      </Select>
                    )}
                  </FormItem>
                </Col>
                <Col span={4} className={styles.labelCol} >
                  <FormItem {...formLayout} style={{ marginRight: '0px' }}>
                    {getFieldDecorator(`amount_${index}`, {
                      initialValue: AccountJS.format(item.price * item.qty, 2),
                    })(<InputNumber style={{ width: '100%' }} size="small" />)}
                  </FormItem>
                </Col>
              </Row>
            })}
        </div>
      </Form></div>
    );

  }
}

export default Comp;

